import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/knowledgeword/folderKnowledgeWordsDto.dart';
import 'package:ichinesereader/models/knowledgeword/knowledgeWord.dart';
import 'package:ichinesereader/models/knowledgeword/shareKnowledgeWordsDto.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/utils/commonApi.dart';
import 'package:file_picker/file_picker.dart';

class KnowledgeWordsServiceProvider extends GetConnect with CommonApi {
  final jsonEncoder = JsonEncoder();
  KnowledgeWordsServiceProvider() {
    httpClient.addResponseModifier((request, response) {
      if (response.statusCode == 403) {
        Log.debug('${request.url} 403 error');
        if (!Get.isSnackbarOpen) {
          Get.snackbar(
            'Message'.tr,
            'You have been logged out due to inactivity or security reasons.'
                .tr,
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Color(0xff23c6c8),
            colorText: Color(0xffd8ffff),
          );
        }
        if (EasyLoading.isShow) {
          EasyLoading.dismiss();
        }
        if (Get.currentRoute != '/login') {
          return Get.offAllNamed('/login');
        }
      } else if (response.statusCode == 401) {
        Log.debug('${request.url} unauthorized access');
        if (!Get.isSnackbarOpen) {
          Get.snackbar('Message'.tr, 'Unauthorized access'.tr,
              backgroundColor: Color(0xff23c6c8),
              colorText: Color(0xffd8ffff),
              snackPosition: SnackPosition.BOTTOM);
        }
        if (EasyLoading.isShow) {
          EasyLoading.dismiss();
        }
        if (Get.currentRoute != '/login') {
          return Get.offAllNamed('/login');
        }
      } else {
        Log.debug(response.request?.url.toString());
        return response;
      }
    });
    httpClient.maxAuthRetries = 2;
    httpClient.timeout = Duration(seconds: 30);
  }

  Future<dynamic> getKnowledgeWordFolderTree() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/knowledge/folder/tree',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getKnowledgeWordTrash() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/knowledge/trash',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getKnowledgeWordQuestions(
      String? bookCode, List<String>? wordIds) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    var profile =
        json.decode(box.get(CacheManagerKey['profilesettings'].toString()));
    var buffer = new StringBuffer();
    if (bookCode == null) {
      wordIds?.forEach((id) {
        buffer.write('wordIds=' + id + "&");
      });
    }
    String temp = buffer.toString();
    var ids = buffer.length == 0 ? temp : temp.substring(0, temp.length - 1);
    String language = profile["language"] ?? 'Simplified';
    String lang = profile["lang"] ?? 'Mandarin';
    var simplified = language.toLowerCase() == "simplified" ? true : false;
    var mandarin = lang.toLowerCase() == "mandarin" ? true : false;
    final response = await get(
      bookCode != null
          ? '${Constants.BaseAPISuper}superadmin/knowledge/word/question?bookCode=$bookCode&simplified=$simplified&mandarin=$mandarin'
          : '${Constants.BaseAPISuper}superadmin/knowledge/word/question?$ids&simplified=$simplified&mandarin=$mandarin',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getKnowledgeWordsByFolder(
      String folderId, String level) async {
    final box = Hive.box('appconfig');

    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());

    final response = await get(
      // '${Constants.BaseAPISuper}superadmin/knowledge/word/folder/$folderId?level=$level',
      '${Constants.BaseAPISuper}superadmin/knowledge/word/folder/$folderId?level=',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getKnowledgeWordsByTeacher(
      String teacherId, String level) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());

    final response = await get(
      '${Constants.BaseAPISuper}superadmin/knowledge/word/share/$teacherId?level=',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> searchKnowledgeWords(String query) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/knowledge/word/search/$query',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> shareKnowledgeWords(ShareKnowledgeWordsDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/knowledge/share',
      shareKnowledgeWordsDtoToJson(dto),
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> uploadKnowledgeFile(PlatformFile pfile) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());

    var request = http.MultipartRequest('POST',
        Uri.parse('${Constants.BaseAPISuper}superadmin/knowledge/file'));
    request.headers
        .addAll({'authtoken': _authtoken, 'content-type': 'image/png'});

    final fileReadStream = pfile.readStream;
    if (fileReadStream == null) {
      throw Exception('Cannot read file from null stream');
    }
    final stream = http.ByteStream(fileReadStream);
    final multipartFile = http.MultipartFile(
      'file',
      stream,
      pfile.size,
      filename: pfile.name,
    );
    request.files.add(multipartFile);

    final response = await request.send();
    return response;
  }

  Future<dynamic> moveKnowledgeWords(FolderKnowledgeWordsDto dto,
      String fromFolderId, String toFolderId, bool keepFlag) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String kFlag = keepFlag ? 'true' : 'false';
    final response = await put(
      '${Constants.BaseAPISuper}superadmin/knowledge/move/$fromFolderId/$toFolderId?keepFlag=$kFlag',
      folderKnowledgeWordsDtoToJson(dto),
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> saveKnowledgeWords(
      List<String>? dto, String toFolderId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/knowledge/word/save/folder/$toFolderId',
      dto,
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> removeKnowledgeWordsFromFolder(
      FolderKnowledgeWordsDto dto, String folderId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // final response = await delete(
    //   '${Constants.BaseAPISuper}superadmin/knowledge/remove/$folderId',
    //   query: <String, dynamic>{
    //     "folderIds": dto.folderIds != null
    //         ? List<dynamic>.from(dto.folderIds!.map((x) => x))
    //         : null,
    //     "knowledgeIds": dto.knowledgeIds != null
    //         ? List<dynamic>.from(dto.knowledgeIds!.map((x) => x))
    //         : null,
    //   },
    //   // query: dto.toJson(),
    //   headers: <String, String>{"authtoken": _authtoken},
    // );
    var request = http.Request(
        'delete',
        Uri.parse(
            '${Constants.BaseAPISuper}superadmin/knowledge/remove/$folderId'));
    request.headers
        .addAll({'authtoken': _authtoken, 'content-type': 'application/json'});
    request.body = jsonEncoder.convert(dto.toJson());
    final response = await request.send();
    return response;
  }

  Future<dynamic> generateAudioByWord(String word) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/knowledge/audio/auto?mandarin=true&text=' +
          word,
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getBasicKnowledgeWords() async {
    final box = Hive.box('appconfig');
    var profile =
        json.decode(box.get(CacheManagerKey['profilesettings'].toString()));

    String language = profile["language"] ?? 'Simplified';
    String lang = profile["lang"] ?? 'Mandarin';
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/knowledge/word/book/basic100?language=English&simplified=$language &mandarin=$lang',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

//{"status":1000,"message":"create knowledge word success","result":{"id":"7c351cbc-b133-4787-85ad-1afadbf51411"}}
  Future<dynamic> createKnowledgeWord(
      KnowledgeWord word, String folderId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/knowledge/word/folder/$folderId',
      knowledgeWordToJson(word),
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> updateKnowledgeWord(KnowledgeWord word) async {
    final box = Hive.box('appconfig');
    String wordId = word.id.toString();
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await put(
      '${Constants.BaseAPISuper}superadmin/knowledge/word/$wordId',
      knowledgeWordToJson(word),
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> createKnowledgeWordFolder(
      String parentFoldId, String folderName) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/knowledge/folder/$parentFoldId',
      '$folderName',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getKnowledgeWordsByBookCode(
      String bookcode, bool simplified, bool mandarin) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String text = 'Simplified';
    String audio = 'Mandarin';
    if (simplified == false) text = 'Traditional';
    if (mandarin == false) audio = 'Cantonese';
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/knowledge/word/book/$bookcode?language=English&simplified=$text&mandarin=$audio',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getKnowledgeDetailsByBookCode(
      String bookcode, bool simplified, bool mandarin) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String text, audio;
    if (simplified)
      text = 'true';
    else
      text = 'false';
    if (mandarin)
      audio = 'true';
    else
      audio = 'false';
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/knowledge/book/$bookcode?language=English&simplified=$text&mandarin=$audio',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getBookFlashCards(String bookCode, String language,
      String textType, String audioType) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    if (bookCode.isEmpty) bookCode = 'BASIC100';
    if (language.isEmpty) language = 'Chinese';
    if (textType.isEmpty) textType = 'Simplified';
    if (audioType.isEmpty) audioType = 'Mandarin';
    Uri url = Uri.parse(
        '${Constants.BaseAPISuper}superadmin/knowledge/word/book/$bookCode?language=$language&simplified=$textType&mandarin=$audioType');
    final response = await http.get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }
}
